import router from './index'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore, useRouterStore } from '@/store'
import type { IMenuEntity } from '@/types'
import { cache, NextLoading } from '@/utils'
import type { IApiData } from '@/service/request/type'

/**需要在菜单显示的页面 */
const viewsModules: Record<string, Function> = import.meta.glob('../view/**/index.vue')
/**内置页面，无需在菜单显示 */
const infoViewsModules: Record<string, Function> = import.meta.glob('../view/**/view-*.vue')

/**
 * 路径转换
 */
const routeViews: Record<string, Function> = {}
for (const k in viewsModules) {
  routeViews[k.replace(/..\/view|../, '').replace('/index.vue', '')] = viewsModules[k]
}

const routerInfoViews: Record<string, Function> = {}
for (const k in infoViewsModules) {
  routerInfoViews[k.replace(/..\/view|../, '').replace('.vue', '')] = infoViewsModules[k]
}

const staticRoutes: RouteRecordRaw[] = [
  {
    name: 'login',
    path: '/login',
    component: () => import('@/view/login/index.vue')
  },
  {
    path: '/:path(.*)*',
    name: 'erro',
    component: () => import('@/components/erro/404.vue'),
    meta: {
      isHide: true
    }
  }
]

/**基础路由， */
const baseRouter: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'base',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    children: []
  }
]

const homePage = [
  {
    id: 'home',
    parentId: '-1',
    name: '主页',
    path: '/home',
    meta: {
      isHide: false,
      isKeepAlive: false,
      icon: 'menu-icon-home'
    },
    menuType: '1',
    sortOrder: 1
  }
]

const infoPage = [
  {
    name: '故障客户清单',
    path: '/fault/statistic-customer/cpns/view-list-all',
    menuType: '2'
  },
  {
    name: '代理客户清单',
    path: '/agent/statistic/cpns/view-list-all',
    menuType: '2'
  }
]

/**
 * 初始化系统数据
 * @returns
 */
const initSystemData = async () => {
  const token = cache.getToken()
  if (!token) return
  const userStore = useUserStore()
  const routerStore = useRouterStore()

  NextLoading.start()

  return new Promise<IApiData>((r, j) => {
    userStore
      .getUserInfo()
      .then(res => {
        if (res.code !== 0) {
          r(res)
          NextLoading.done()
          return
        }
        userStore.setUserInfo(res.data)

        let menuList = JSON.parse(JSON.stringify(res.data.menuList))
        if (!menuList?.length) menuList = []

        // 前端写死的页面
        menuList.unshift(...homePage)
        // 内部打开页面不在左侧菜单显示
        menuList.push(...infoPage)

        // 获取过滤后的菜单和权限
        const permission: string[] = []
        const filterMenuList = filterMenu(menuList, permission)

        // 菜单与组件映射
        const list = backEndComponent(filterMenuList)

        baseRouter[0].children = list

        // 路由注册
        router.addRoute(baseRouter[0])

        const columnPageFilter = cache.get('columnPageFilter')

        userStore.setByKey('columnPageFilter', columnPageFilter ?? {})

        userStore.setByKey('permission', permission)
        routerStore.setRouterList(filterMenuByType(filterMenuList))

        r(res)
      })
      .catch(() => {
        j()
        NextLoading.done(500)
      })
  })
}

/**
 * 过滤菜单与权限
 * @param rawMenu
 * @returns
 */
const filterMenu = (rawMenu: IMenuEntity[], permission: string[]) => {
  return rawMenu.filter(item => {
    if (item.menuType === '0') permission.push(item.permission)

    if (item.children?.length) item.children = filterMenu(item.children, permission)

    return ['1', '2'].includes(item.menuType) && !item.meta?.isHide
  })
}
/**
 * 过滤菜左侧菜单
 * @param rawMenu
 * @returns
 */
const filterMenuByType = (rawMenu: IMenuEntity[]) => {
  return rawMenu.filter(item => {
    if (item.children?.length) item.children = filterMenuByType(item.children)
    return item.menuType === '1' && !item.meta?.isHide
  })
}

/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
const backEndComponent = (routes: IMenuEntity[]) => {
  if (!routes) return
  return routes.map((item: any) => {
    if (item.path) {
      item.component = dynamicImport(item.menuType === '1' ? routeViews : routerInfoViews, item.path)
    }

    if (item.children?.length) {
      backEndComponent(item.children)
      item.redirect = item.children[0].path
    }

    return item
  })
}

/**
 * 后端路由 component 转换函数
 * @param routeViews 获取目录下的 index.vue 全部文件
 * @param path 当前要处理项 path
 * @returns 返回处理成函数后的 component
 */
const dynamicImport = (viewsModules: Record<string, Function>, path: string) => {
  const component = viewsModules[path] ?? false

  return component
}

export { staticRoutes, initSystemData, baseRouter }
